{% extends "base.html" %}

{% block head %}
  <script>
  var semester = 201201;
  $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
  var tabCount = 1;
  var limit = 1;
  var test = false;
  var lastSearch;
  
  //colors used for tabs. 
  var color_array = ['#B32D00','#F03C00','#00B32D','#00B386','#0086B3'];
  var tab_colors = [];
  var lastPressed = [];
  var tabs = [];
  var lastTab = "#tab1";
  var dialogue = true;
  
  function openPopUp(){
    $(".popUp #message").fadeIn("fast");
    $(".screen").fadeIn("fast");  
  }

  function closePopUp(){
    $(".popUp #message").fadeOut("fast");
    $(".screen").fadeOut("fast");  
  }
  
  $(document).bind('keydown',function(e) {
    if(e.keyCode == 13){
      $(lastTab+ "submit").click();
    }
  });

  
  var todate = function(timestamp, weekday, offsetmin) {
    var now = new Date();
    var D = now.getDate();
    var M = now.getMonth();
    var Y = now.getFullYear();
    var H = parseInt(timestamp.substr(0,2), 10);
    var m = parseInt(timestamp.substr(2,2), 10);
    var w = "SMTWRF".indexOf(weekday);
    var x = new Date(Y, M, D + (w-now.getDay()), H, m);
    if(offsetmin != null) {
      y = new Date();
      y.setTime(x.getTime() + (offsetmin*60*1000));
      return y;
    } else
      return x;
  }

  /* Renders the program maps list from JSON
   * 
   */
  var render_program_maps = function(data) {
    var ul = $("#programs ul");
    if(data.error) {
      var li = $("<li>");
      li.append("Error:" + data.error);
      ul.append(li);
    } else {
      $.each(data.response, function(i, p) {
        var li = $("<li>")
        .append("[" + p.dept + "] " + p.progdesc)
        .addClass("program-map-entry")
        .data({
          type: "p",
          data: p
        });
        ul.append(li);
      });
    }
  };
  /* Renders the course selection list from JSON
   * 
   */
  var render_courses = function(data) {
    var ul = $("#courses ul");
    if(data.error) {
      ul.append("<li>" + data.error + "</li>");
    } else {
      $.each(data.response, function(i, c) {
        if(c.title) {
          var li = $("<li>")
            .append(c.code + ": " + c.title)
            .addClass("course-entry")
            .data({
              type: 'c',
              data: c
            });
          ul.append(li);
        }
      });
    }
  };
  
  var make_calendar = function(opt) {  
    var div = opt.div;
    var eraseheader = opt.eraseheader;
    var renderer = opt.renderer;
    var onclick = opt.onclick;
    var f;
    if(renderer != null) {
      f = function(ev, elem) {
        $(elem).addClass("calendar-event").data("_id", ev._id);
        return renderer(ev, elem);
      };
    } else {
      f = function(ev, elem) {
        $(elem).addClass("calendar-event").data("_id", ev._id);
      }
    }
    var o = {
      header: {
        left: '',
        center: '',
        right: ''},
      defaultView: 'agendaWeek',
      allDaySlot: false,
      weekends:false,
      minTime: 8,
      maxTime: 23,
      aspectRatio: 0.5,
      events: [],
      eventRender: f
    };
    if(onclick) {
      o.eventClick = onclick;
    }
    $(div).fullCalendar(o);
    // Remove date from the weekday heading
    $("thead .fc-widget-header", $(div)).each(function(i, e) {
      if(eraseheader == 'erase')
        $(this).html("-");
      else {
        var text = $(this).text();
        if(text.length > 0) $(this).html(text.substr(0, 3));
      }
    });
    // Remove scrolling
    $('.fc-view-agendaWeek > div > div', div).css('overflow-y', 'hidden');
    $('.fc-agenda-gutter', div).css('width', 0);
    // Remove background coloring for inner
    $(".fc-event-inner").css('background-color', null);
  };

  
  /* Display loading message and calls fetch_schedule
   * after fetch_schedule completes, clears the loading message
   * e = value from input box
   */
  var loading_schedule = function(e) {
    $("div.message").html("Loading...");
    $.when(fetch_schedule(e)).then(function() {
      $("div.message").empty();
    });  
  };
  
  /* Run get_schedule on the input
   * e = value from input box
   */
  var fetch_schedule = function(e) {
    lastSearch = e.attr('value');
    return $.ajax({
		url: "{{url_for('get_events')}}", 
		data: {semester: semester, search: e.attr('value')},
		dataType: 'json',
		success: function(data) {
			if(data.evtype == 'free')
				render_events('free', data);
			else if(data.evtype == 'clear'){
        //$(lastTab+ "Cal").fullCalendar( 'removeEvents');
        //alert("here1");                                        <-------------fix this
      }else{
				render_events('sched', data);
      }
		}
	  });
  }; 
  
  var render_events = function(evtype, data) {
    if(data.error) {
      alert("error: " + data.error);
      return;
    }
    var events = [];
    var groupby = {};
    var codes = [];
    $.each(data.response, function(i, e) {
      e.evtype = evtype;
      var start = todate(e.btime, e.day);
      var end, title;
      if(evtype == 'free') {
        end = todate(e.btime, e.day, e.duration);
        title = e.numlocs;
      }
      else {
        end = todate(e.etime, e.day);
        title = e.code;
      }

      if(e.btime != null) {
        var ev = {
          title: title,
          start: start,
          end: end,
          allDay: false,
          color: lastPressed,
          info: e
          };
        events.push(ev);
        if(!groupby[e.code]) {
          groupby[e.code] = [];
          codes.push(e.code);
        }
        groupby[e.code].push(e);
      }
    });
    $(lastTab+ "Cal")
      .fullCalendar("removeEvents")
      .fullCalendar("addEventSource", events)
      .fullCalendar("render");
      
  };
  
  $(document).ready(function() {
    $("#tabs").tabs();
    $.getJSON("{{url_for('program_maps')}}",
      {semester: semester}, render_program_maps);
    $.getJSON("{{url_for('courses')}}",
      {semester: semester}, render_courses);

    $( "#accordion" ).accordion({
			active: false,
      collapsible: true
		});
    
    var $tab_title_input = $( "#tab_title"),
	  $tab_content_input = $( "#tab_content" );

		// tabs init with a custom tab template and an "add" callback filling in the content
		var $tabs = $( "#tabs").tabs({
			tabTemplate: "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
			add: function( event, ui ) {
				var tab_content = $tab_content_input.val() || "<input type='text' class='span8' id='searchbox'></input>&nbsp&nbsp<button id='tab" + tabCount + "submit' >Enter</button><br/><br/>";
				$( ui.panel ).append( "<p>" + tab_content + "</p>" );
			},
			select: function(ev, ui) {
				var panel = $(ui.panel);
				var tabId = panel.attr('id');
				var calendar = $("#" + tabId + "Cal");
				if(calendar.size() > 0) {
					$("div.calendar").css('z-index', 1);
					calendar.closest("div.calendar").css('z-index', 10);
				}
			}
		});
    
    var $dialog = $( "#dialog" ).dialog({
			autoOpen: false,
			modal: true,
			buttons: {
				Add: function() {
					addTabFunc();
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			},
			open: function() {
				$tab_title_input.focus();
			},
			close: function() {
			
			}
		});
    
    var $dialog2 = $( "#dialog2" ).dialog({
			autoOpen: false,
			modal: true,
			open: function() {
				$tab_title_input.focus();
			},
			close: function() {			
			}
		});

      
    /* Creates a new tab and sets the color
     * color is picked from a "inactive" array and set to the "active" array
     */
    function addTabFunc() {
      var tab_title = $tab_title_input.val() || "Tab " + tabCount;
      $tabs.tabs( "add", "#tab" + tabCount, tab_title );
      var color = color_array.pop();
      tab_colors.push(color);
      var cssObj = {
        'background-color' : color,
        'color' : '#000'
      }
      $("#tabs ul a:last").css(cssObj);
      $("#tab"+tabCount).css({
        background: color
      });
      $("#tab"+tabCount+"submit")
        .button()
        .click(function() {
          loading_schedule($(this).prev());
          lastPressed = color;
          lastTab = "#tab"+ (tabCount-1);
        });
        $tabs.tabs( "select" , limit-1 );
        tabs.push("tab" + tabCount);
      $('.calendars').append("<div class='calendar'><div id='tab" + tabCount + "Cal'></div></div>");
      make_calendar({
        div: "#tab" + tabCount + "Cal",  
        renderer: function(ev, elem) {
          var dataContent;
          if(! ev.info.code) {
            dataContent = "There are <b>" 
                        + ev.info.numlocs + "</b> free locations";
            $(elem).click(function() {
              openPopUp();
              return $.ajax({                                                                           // <------------------------ fix this
                url: "{{url_for('get_events')}}", 
                data: {semester: semester, search: "free btime:" + ev.info.btime + " day:" + ev.info.day},
                dataType: 'json',
                success: function(data) {
                  var $msg = $("#message");
                  if(data.error)
                    $msg.html("Error:" + data.error);
                  else {
                    var $ul = $(".room-list", $msg);
                    var n = data.response.length;
                    var title;
                    if(n == 0)
                      title = "There are no free rooms."
                    else {
                      title = "There are " + n + " rooms at " 
                            + data.response[0].btime + " for " 
                            + data.response[0].duration + " minutes.";
                    }
                    $("h1", $msg).html(title);
                    $.each(data.response, function(i, x) {
                      if(x.location) $("<li>").html(x.location).appendTo($ul);
                    });
                  }
                }
              });
              
            });
          } else {
            dataContent = "<i>" + ev.info.title + "</i>," + 
              "<b>" + ev.info.schd + "</b> at " + 
              "<span style='font-size:120%'>" + ev.info.location + "</span>";
          }
          $(elem).attr({
            title: ev.title,
            'data-content': dataContent
          });
          $(elem).popover({html: true});
        }
      });
      tabCount++;
      limit++;    
    }

		// close icon: removing the tab and calendar on click 
		$( "#tabs span.ui-icon-close" ).live( "click", function() {
			var index = $( "li", $tabs ).index( $( this ).parent() );
			//$("#" + tabs[index] + "Cal").closest("div.calendar").remove();
      $("#" + tabs[index] + "Cal").parent().remove();
			tabs.splice(index,1); //remove from tab array
			$tabs.tabs( "remove", index ); //remove tab
			var color = tab_colors[index]; //store color
      tab_colors.splice(index,1); //remove color from active array
      color_array.push(color); //place color back in inactive array
      limit--;
		});
    
    // addTab button: just opens the dialog
		$( "#add_tab" )
			.button()
			.click(function() {
        if(limit <= 5)
          $dialog.dialog( "open" );
        else
          //max tabs reached
          $dialog2.dialog( "open");
			});
    $(".popUpClose").click(function() {
      closePopUp();
    });
  
    $(".screen").click(function(){  
      closePopUp();  
    });
    
    //Create an initial Tab
    addTabFunc();
    
  });
  
  </script>
  <style type="text/css">
  #dialog label, #dialog input { display:block; }
	#dialog label { margin-top: 0.5em; }
	#dialog input, #dialog textarea { width: 95%; }
  #tabs { margin-top: 1em; }
	#tabs li .ui-icon-close { float: left; margin: 0.4em 0.2em 0 0; cursor: pointer; }
  #tab1{
    background:#5CB3FF;
  }
  #tabs ul a{
    background: #5CB3FF;
    color:#000;
  }
  .calendars {
    position: relative;
    width: 940px;
  }
  .calendar {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100%;
    opacity: 0.8;
  }
  #message {
    height: 400px;
    overflow: auto;
    
  }
  #message h1 {
    font-size: 14pt;
  }
  ul.room-list {
    list-style-type: none;
  }
  ul.room-list li {
    font-family: Consolas, "Courier New", monospace;
    font-weight: bold;
    font-size: 12pt;
    display: inline-block;
    padding: 5px 5px 5px 5px;
    margin: 5px 5px 5px 5px;
    background: #000;
    border-radius: 5px;
    color: #fff;
  }
  
  </style>
{% endblock %}

  <body>
    {% block body %}
      <div id="dialog" title="Tab data">
        <form>
          <fieldset class="ui-helper-reset">
            <label for="tab_title">Title</label>
            <input type="text" name="tab_title" id="tab_title" value="" class="ui-widget-content ui-corner-all" />
          </fieldset>
        </form>
      </div>
      <div id="dialog2" title="Attention">
        <fieldset class="ui-helper-reset">
            <label >Max Tabs Reached</label>   
        </fieldset>
      </div>
      
      <div class="container">
      <div class="popUp">
        <div id="message"> 
          <a class="popUpClose">x</a>
          <h1></h1>
          <ul class="room-list"></ul>          
        </div>
      <div class="screen"></div>  
    </div>
        <div class="content">
          <div class="span16">
            <div class="row">
              <div class="span16">
                <button id="add_tab">Add Tab</button>
                <div id="tabs">
                  <ul>                
                               
                  </ul>           
                </div>
                
                <div id="accordion">              
                    <h3><a href="#">Courses</a></h3>
                    <div id="courses">
                      <div class="scrolled-view">
                        <ul></ul>
                      </div>
                    </div>
                </div> 
                
                <div class="message"></div><br/>
                  <div class="calendars">
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>


      </div> <!-- /container -->
    {% endblock %}
  </body>
</html>
